﻿using System;
using System.Collections.Generic;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using NCS.IConnect.ApplicationContexts;
using Microsoft.SharePoint;
using JM.JCY.Proxy;
using JM.JCY.BusinessEntity;
using JM.JCY.Common;
using System.Data;
using JM.JCY.Common.Utilities;
using System.IO;
using System.Threading;
using System.Text;
using System.Globalization;

namespace JM.JCY.SharePointComponent.PhotoAlbum.ViewAllAlbums
{
    public partial class ViewAllAlbumsUserControl : UserControl,ICallbackEventHandler
    {
        static int PAGESIZE = JCYConstant.Pagination.ViewAllAlbumPageSize;
        private int currentPageIndex;
        public string lastIndex = "1";
        public string appType
        {
            set;
            get;
        }
        public int appId
        {
            set;
            get;
        }
        public int _staffId
        {
            set;
            get;
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                LoadApplicationContext();
                Session["AlbumDT"] = null;
                BindList(1, true);
                string callbackReference = Page.ClientScript.GetCallbackEventReference(this, "arg", "ReceiveCallback", "context", false);
                string callbackScript = string.Format("function CallServer(arg,context){{ {0}  }}", callbackReference);
                Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "CallServer", callbackScript, true);
            }
        }

        private void LoadApplicationContext()
        {
            _staffId = 11;
            if (ApplicationContext.Current.GetKeyValue("userId") != null)
            {
                _staffId = Convert.ToInt32(ApplicationContext.Current.GetKeyValue("userId"));
            }

            if (ApplicationContext.Current.GetKeyValue("appType") != null)
            {
                appType = ApplicationContext.Current.GetKeyValue("appType").ToString();
            }
            HiddenFieldWC.Value = "F";
            switch (appType)
            {
                case JCYConstant.PhotoAlbum.ApplicationTypeName.PublicName:
                    appId = 0;
                    break;
                case JCYConstant.PhotoAlbum.ApplicationTypeName.PersonalName:
                    appId = _staffId;
                    break;
                case JCYConstant.PhotoAlbum.ApplicationTypeName.WorkgroupName:
                    if (ApplicationContext.Current.GetKeyValue("AppId") != null)
                    {
                        appId = Convert.ToInt32(ApplicationContext.Current.GetKeyValue("AppId"));
                    }
                    HiddenFieldWC.Value = "T";
                    break;
                case JCYConstant.PhotoAlbum.ApplicationTypeName.CommitteeName:
                    if (ApplicationContext.Current.GetKeyValue("AppId") != null)
                    {
                        appId = Convert.ToInt32(ApplicationContext.Current.GetKeyValue("AppId"));
                    }
                    HiddenFieldWC.Value = "T";
                    break;
            }
        }
        protected void DataList_ItemDataBound(object sender, DataListItemEventArgs e)
        {
            //Label lblContext = (Label)e.Item.FindControl("lblContext");
            //Image imgContext = (Image)e.Item.FindControl("imgContext");
        }

        protected void BindList(int pageIndex, bool needRender)
        {
            PhotoAlbumSearchDataSet.T_AlbumDataTable AlbumDT = new PhotoAlbumSearchDataSet.T_AlbumDataTable();
            if (ViewState["AlbumDT"] == null)
            {
                string AlbumType = string.Empty;
                string type = Request.QueryString["Type"];
                int appid = 0;
                string objectName = "";
                if (Request.Params["appid"] != null)
                {
                    appid = Convert.ToInt32(Request.QueryString["appid"]);

                    using (UserManagementProxy proxy = new UserManagementProxy())
                    {
                        if (type == "W")
                        {
                            DataSetUserManagement.T_DepartmentDataTable dept = proxy.GetDeptById(appid,"");
                            if (dept.Rows.Count == 1)
                            {
                                objectName = dept[0].DeptName;
                            }
                        }

                        if (type == "C")
                        {
                            CommitteeDataSet.T_CommitteeDataTable committee = proxy.GetCommitteeById(appid);
                            if (committee.Rows.Count == 1)
                            {
                                objectName = committee[0].CommitteeName;
                            }
                        }
                    }
                }
                
                using (PhotoAlbumProxy proxy = new PhotoAlbumProxy())
                {
                    if (type == "P")    //all public
                    {
                        AlbumDT = proxy.GetAllPublicAlbums(JCYConstant.PhotoAlbum.ApplicationTypeName.PublicName, 0);
                        lblTitle.Text = "所有公开的相册";
                    }

                    if (type == "W")    //all public
                    {
                        AlbumDT = proxy.GetAllPublicAlbums(JCYConstant.PhotoAlbum.ApplicationTypeName.WorkgroupName, appid);

                        lblTitle.Text = objectName + " 部门的相册";
                    }

                    if (type == "C")    //all public
                    {
                        AlbumDT = proxy.GetAllPublicAlbums(JCYConstant.PhotoAlbum.ApplicationTypeName.CommitteeName, appid);
                        lblTitle.Text = objectName + " 专题小组的相册";
                    }

                    else if (type == "PS")    //My Contributions
                    {
                        AlbumDT = proxy.GetMySelfAlbums(JCYConstant.PhotoAlbum.ApplicationTypeName.PersonalName, _staffId, _staffId);

                        lblTitle.Text = "我私人的相册";

                    }

                    dlResult.DataSource = AlbumDT;
                    dlResult.DataBind();


                    ViewState["AlbumDT"] = AlbumDT;
                }
            }
            else
            {
                AlbumDT = (PhotoAlbumSearchDataSet.T_AlbumDataTable)ViewState["AlbumDT"];
            }

            //Calculate total page count
            int pages = (AlbumDT.Rows.Count % PAGESIZE == 0) ? AlbumDT.Rows.Count / PAGESIZE : (AlbumDT.Rows.Count / PAGESIZE) + 1;
            lastIndex = pages.ToString();
            HiddenFieldPageNum.Value = pages.ToString();

            if (pageIndex > pages)
                pageIndex = pages;
            else if (pageIndex < 1)
                pageIndex = 1;
            int startId = (pageIndex - 1) * PAGESIZE;
            int endId = pageIndex * PAGESIZE - 1;

            DataRow[] rows = AlbumDT.Select(string.Format("id>={0} and id<={1}", startId, endId));
            dlResult.DataSource = rows;
            dlResult.DataBind();
        }

        public string GetCallbackResult()
        {
            //Return the rebind datalist's content
            return RenderControl(dlResult);
        }

        //Realize ICallbackEventHandler member RaiseCallbackEvent
        public void RaiseCallbackEvent(string eventArgument)
        {
            currentPageIndex = Convert.ToInt32(eventArgument);
            BindList(currentPageIndex, false);
        }

        private string RenderControl(Control control)
        {
            StringWriter writer1 = new StringWriter(CultureInfo.InvariantCulture);
            HtmlTextWriter writer2 = new HtmlTextWriter(writer1);

            control.RenderControl(writer2);
            writer2.Flush();
            writer2.Close();

            return writer1.ToString();
        }
    }
}
